import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    nav:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_NAV: (state, nav) => {
    state.nav = nav
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        if (response.errcode == 0) {
          commit('SET_TOKEN', response.data.token)
          setToken(response.data.token)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user token
  token({ commit }, token) {
    commit('SET_TOKEN', token)
    setToken(token)
  },

  // user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(Object.assign({ sign: Md5(objKeySort(apiUrl().name) + apiUrl().appsecret) },apiUrl().name)).then(response => {
        commit('SET_NAME', response.data.userInfo.name)
        commit('SET_AVATAR', response.data.userInfo)
        commit('SET_NAV', response.data.nav)
        console.log(response.data.nav, '获取的数据')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },


  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(Object.assign({ sign: Md5(objKeySort(apiUrl().name) + apiUrl().appsecret) },apiUrl().name)).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

